#!/usr/bin/env node
/**
 * Phase2 UI Diff 生成器
 * 用法：node scripts/phase2/generate-ui-diff.js ComponentName [baseScreenshot] [localScreenshot]
 *
 * 默认基准图：ComponentName/phase1/screenshots/main.png
 * 默认对比图：ComponentName/phase2/screenshots/{ComponentName}_local.png
 * 产物：phase2/ui-diff.json + phase2/screenshots/{ComponentName}_diff.png
 */

const fs = require('fs');
const path = require('path');

let pixelmatch;
let pngjs;

try {
  pixelmatch = require('pixelmatch');
  pngjs = require('pngjs');
} catch (err) {
  console.error('❌ 依赖缺失：需要安装 pixelmatch 与 pngjs');
  console.error('执行：npm install --save-dev pixelmatch pngjs');
  process.exit(1);
}

const { PNG } = pngjs;

function loadPng(filePath) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`截图不存在: ${filePath}`);
  }
  const buffer = fs.readFileSync(filePath);
  return PNG.sync.read(buffer);
}

function ensureDir(filePath) {
  const dir = path.dirname(filePath);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
}

function buildDiffReport(componentName, baseScreenshot, localScreenshot, diffPngPath, similarity, diffPixels) {
  return {
    timestamp: new Date().toISOString(),
    component: componentName,
    method: 'pixelmatch',
    threshold: 0.1,
    similarity: Number(similarity.toFixed(4)),
    diffPixels,
    screenshot_base: path.relative(process.cwd(), baseScreenshot),
    screenshot_local: path.relative(process.cwd(), localScreenshot),
    diffImage: path.relative(process.cwd(), diffPngPath),
    differences: []
  };
}

function main() {
  const componentName = process.argv[2];
  const baseScreenshotArg = process.argv[3];
  const localScreenshotArg = process.argv[4];

  if (!componentName) {
    console.error('用法: node scripts/phase2/generate-ui-diff.js <ComponentName> [baseScreenshot] [localScreenshot]');
    process.exit(1);
  }

  const root = process.cwd();
  const componentRoot = path.join(root, componentName);

  const baseScreenshot = baseScreenshotArg
    ? path.resolve(baseScreenshotArg)
    : path.join(componentRoot, 'phase1/screenshots/main.png');

  const localScreenshot = localScreenshotArg
    ? path.resolve(localScreenshotArg)
    : path.join(componentRoot, `phase2/screenshots/${componentName}_local.png`);

  const diffPngPath = path.join(componentRoot, `phase2/screenshots/${componentName}_diff.png`);
  const diffJsonPath = path.join(componentRoot, 'phase2/ui-diff.json');

  try {
    console.log(`\n📸 生成 UI Diff (Component: ${componentName})`);
    console.log(`  基准截图: ${baseScreenshot}`);
    console.log(`  本地截图: ${localScreenshot}`);

    const baseImage = loadPng(baseScreenshot);
    const localImage = loadPng(localScreenshot);

    if (baseImage.width !== localImage.width || baseImage.height !== localImage.height) {
      throw new Error(`截图尺寸不一致: base=${baseImage.width}x${baseImage.height}, local=${localImage.width}x${localImage.height}`);
    }

    const { width, height } = baseImage;
    const diff = new PNG({ width, height });

    const diffPixels = pixelmatch(
      baseImage.data,
      localImage.data,
      diff.data,
      width,
      height,
      { threshold: 0.1 }
    );

    const totalPixels = width * height;
    const similarity = 1 - diffPixels / totalPixels;

    ensureDir(diffPngPath);
    const diffBuffer = PNG.sync.write(diff);
    fs.writeFileSync(diffPngPath, diffBuffer);

    const report = buildDiffReport(
      componentName,
      baseScreenshot,
      localScreenshot,
      diffPngPath,
      similarity,
      diffPixels
    );

    ensureDir(diffJsonPath);
    fs.writeFileSync(diffJsonPath, JSON.stringify(report, null, 2));

    console.log(`  ✅ 视频对比完成，相似度 ${(similarity * 100).toFixed(2)}%`);
    console.log(`  ✅ 报告写入 ${diffJsonPath}`);
  } catch (error) {
    console.error(`❌ 生成 UI Diff 失败: ${error.message}`);
    process.exit(1);
  }
}

main();
